package be.ipl.diavoloz.servlets;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import be.ipl.diavoloz.usecases.GestionConnexion;
import be.ipl.diavoloz.usecases.GestionInscription;

/**
 * Servlet implementation class Connexion
 */
@WebServlet("/connex.html")
public class Connexion extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@EJB
	private GestionConnexion gestionConn;
	// Test
	@EJB
	private GestionInscription gestionIns;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Connexion() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// if(!gestionIns.sinscrire("popo", "email@gmail.com", 14, "deviner")){
		// getServletContext().getNamedDispatcher("inscription.html").forward(request,
		// response);
		// } else {
		// getServletContext().getNamedDispatcher("index.html").forward(request,
		// response);
		// }
		
		if (gestionConn.authentifierJoueur(request.getParameter("nameConn"),
				request.getParameter("pwdConn"))) {
			synchronized (request.getSession()) {
				request.getSession().setAttribute("connected", true);
				request.getSession().setAttribute("nameConn",
						request.getParameter("nameConn"));
			}
			// Joueur j =
			// gestionConn.verifierJoueur(request.getParameter("nameConn"));
		} else {
			request.getSession().invalidate();
			request.getSession().setAttribute("message",
					"Votre pseudo ou mot de passe n'est pas valide");
		}
		getServletContext().getNamedDispatcher("index.html").forward(request,
				response);
	}
}
